/**
 * 创建人:  @author huangpeng    
 * 创建时间:  2023年11月05日 15:22
 * 项目名称:  lemon-blog-cloud
 * 文件名称:  ExecutorConfig
 * 文件描述:  @Description: 异步线程配置
 * <p>
 * All rights Reserved, Designed By huangpeng 
 * @Copyright: 2021-2023
 *
 */
package com.lemon.message.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 包名称：com.lemon.message.config
 * 类名称：ExecutorConfig
 * 类描述：异步线程配置
 * 创建人：@author huangpeng
 * 创建时间：2023年11月05日 15:22
 */
@EnableAsync
@Configuration
public class ExecutorConfig extends AsyncConfigurerSupport {

    /**
     * 设置线程池大小
     **/
    private static final int corePoolSize = 4;
    /**
     * 设置线程池最大数量
     **/
    private static final int maxPoolSize = 16;
    /**
     * 线程池阻塞队列的容量
     **/
    private static final int queueCapacity = 10;
    /**
     * 线程名称前缀
     */
    private static final String threadNamePrefix = "EmailAsyncExecutor-";

    @Bean("EmailAsync")
    public ThreadPoolTaskExecutor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix(threadNamePrefix);
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //一定要等线程执行完成的时候才去关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //最大等待时间60s
        executor.setAwaitTerminationSeconds(60);
        //项目启动的时候就初始化线程池，避免到调用的时候才初始化
        executor.initialize();
        return executor;
    }

}
